package hash;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description: 383.赎金信
 * User: Li_yizYa
 * Date: 2025—04—02
 * Time: 21:37
 */
public class Solution6 {
    public static void main(String[] args) {
        String str1 = "aa";
        String str2 = "aba";
        System.out.println(canConstruct(str1, str2));
    }

    private static boolean canConstruct(String ransomNote, String magazine) {
        if (magazine.length() < ransomNote.length()) {
            return false;
        }
        int[] record = new int[26];
        for (char c : magazine.toCharArray()) {
            record[c - 'a']++;
        }

        for (char c : ransomNote.toCharArray()) {
            record[c - 'a']--;
        }

        for (int i : record) {
            if (i < 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 哈希表解法
     * @param ransomNote
     * @param magazine
     * @return
     */
    private static boolean canConstruct1(String ransomNote, String magazine) {
        if (ransomNote == null || ransomNote.length() == 0 || magazine == null || magazine.length() == 0) {
            return false;
        }
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < magazine.length(); i++) {
            char c = magazine.charAt(i);
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        for (int i = 0; i < ransomNote.length(); i++) {
            char c = ransomNote.charAt(i);
            if (map.containsKey(c) && map.get(c) > 0) {
                map.put(c, map.get(c) - 1);
            } else {
                return false;
            }
        }
        return true;
    }

}
